
package org.rust.lang;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Rst
{
  
   public String evaluate(char[] src)
   {
     print("Original Source"); 
     print(new String(src));
     Node srcNode = new Node(Node.Type.LIST, null, null, src, 0, src.length - 1);
     srcNode.parse();
     print("After parse");
     print("--------------------------------");
     srcNode.print();
     srcNode.removeRedundantNodes();
     print("After remove redundant");
     print("--------------------------------");
     srcNode.print();
     srcNode.infixToPrefix();
     print("After infix to prefix");
     print("--------------------------------");
     srcNode.print();
     //for the moment we keep digging until we find a function and return the value of that.
     int i = 0;
     Node funcOrItem = srcNode;//.children.get(i);
     //while(funcOrItem != null && funcOrItem.getType() == Node.Type.LIST)
     //   funcOrItem = funcOrItem.children.get(i);
     Node res = funcOrItem.evaluate(null);
     print("program result:" + res.getValue());

     return res.getValue();
   }
   
   
   public static String execScript(String filePath) throws IOException
   {
      
      print("Running " + filePath);
      File f = new File(filePath);
      BufferedReader in = new BufferedReader(new FileReader(f));
      
      char[] src = new char[(int)f.length()]; 
      in.read(src);
      
      String header = "";
      String dbg = " "; 
      for(int i = 0; i < src.length; i++ )
      {
         if(i < 10)
            header += "0" + i + " " ;
         else
            header += i + " ";
         
         dbg +=  src[i] + "  " ;
      }
      
      print(header);
      print(dbg);
      
      return new Rst().evaluate(src);
   }

   public static String exec(String src) 
   {
      return exec(src.toCharArray());
   }

   public static String exec(char[] src)
   {
      
      String header = "";
      String dbg = " "; 
      for(int i = 0; i < src.length; i++ )
      {
         if(i < 10)
            header += "0" + i + " " ;
         else
            header += i + " ";
         
         dbg +=  src[i] + "  " ;
      }
      
      print(header);
      print(dbg);
      
      return new Rst().evaluate(src);
   }

   
	public static void main(String[] args) throws IOException
	{
	   if(args.length < 1)
	   {
	      System.out.println("Enter the path to a rust file");
	      return;
	   }
	   
	   String filePath = args[0];
	   
	   execScript(filePath);
	}
	

	
	
	public static void print(String s)
	{
	   System.out.println(s);
	}
}